package xyz.hujf.base.badlock;

/**
 * @author Hujf
 * @title: DeadLockTest
 * @date 2021-04-239:23
 * @description:
 *
 *
 * 如何避免以下死锁   资源申请有序
 */
public class DeadLockTest {

    private static Object resA= new Object();
    private static Object resB = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            synchronized (resA){
                System.out.println("线程A获取到A锁，等待B锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (resB){
                    System.out.println("获得B锁");
                }
            }
        });

        Thread t2 = new Thread(()->{
            synchronized (resB){
                System.out.println("线程B获取到B锁，等待A锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (resA){
                    System.out.println("线程NB获取A锁");
                }

            }


        });

        t1.start();
        t2.start();


    }
}
